import md5 from 'blueimp-md5'
import constant from '@/utils/constant'
function getSign(array) {
  array.sort(by('key'))
  array.push({ key: 'key', value: constant.API_KEY })
  let str = getSignString(array)
  console.log('要计算sign的字符串为:' + str)
  return md5(str).toUpperCase()
}
var by = function(name) {
  return function(o, p) {
    var a, b
    if (typeof o === 'object' && typeof p === 'object' && o && p) {
      a = o[name]
      b = p[name]
      if (a === b) {
        return 0
      }
      if (typeof a === typeof b) {
        return a < b ? -1 : 1
      }
      return typeof a < typeof b ? -1 : 1
    }
  }
}
var getSignString = function(array) {
  let str = ''
  for (var i in array) {
    str = str + array[i].key + '=' + array[i].value
    if (i < array.length - 1) {
      str = str + '&'
    }
  }

  return str
}

module.exports = {
  getSign: getSign
}
